package util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;

import requisicao.Requisicao;

public class Util {
	
	public static boolean validarServico(Requisicao requisicao){
		String arquivoBase = "conf.properties";		
		Path path  = Paths.get(arquivoBase);
		String caminho = path.toAbsolutePath().toString().substring(0,path.toAbsolutePath().toString().length()-arquivoBase.length())+"src\\servicos\\ ";	
		caminho = caminho.replace("\\", "\\\\");			
		File dir = new File(caminho);
		File[] files = dir.listFiles();
		for (File file2 : files) {
			if(file2.getName().toString().equals(requisicao.getCabecalho().getRecurso().toString().substring(1)+".java")){
				return true;
			}
		}	
		return false;
	}
	public static String getServico(Requisicao requisicao){		
		return requisicao.getCabecalho().getRecurso().toString().substring(1)+".java";	
	}
	public static String lerLinha(InputStream in) throws IOException{
		StringBuilder sb = new StringBuilder();
		
		int b = 0;
		do {
			try {
				b = in.read();
				
				if (b == -1) throw new IOException("Invalid input data");
				
				if (b != '\r' && b != '\n') {
					sb.append((char) b);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
					
		} while (b != '\n');
		return sb.toString();
	}
	
	public static String lerString(InputStream in, int length) throws IOException {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < length; i++) {
			int b = in.read();	
			if (b == -1) throw new IOException("Invalid input data");
			sb.append((char) b);
		}
		byte bytes[] = sb.toString().getBytes();
		
		
		return new String(bytes, "UTF-8");
	}
}
